//导入Vue
import Vue from 'vue'
//导入VueRouter
import VueRouter from 'vue-router'
import routes from '@/router/routes'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
//设置VueRouter到Vue中
Vue.use(VueRouter)
//创建vueRouter对象,参数是一个配置对象,配置对象中常见的属性如下
// mode:路由模式，路由模式常见有两种，一种是hash模式,另外一种是history
// routes:路由配置集合,它是一个数组，该数组中用来管理路由配置对象的
const router = new VueRouter({
    base:'studentMgr',
    mode:'history',
    routes
})
NProgress.configure({ easing: 'ease', speed: 500, showSpinner: false })
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    next()
    let whiteList = ['/login', '/register']
    //获取token
    const token = localStorage.getItem('token')
    //判断token是否存在
    if (token) {
        try {
            await Vue.prototype.$api.users.getUserInfoApi()
            next()
        } catch (error) {
            Vue.prototype.$message.warning('token失效,请重新登录')
            localStorage.removeItem('token')
            next('/login')
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next("/login")
        }
    }
})
router.afterEach(() => {
    NProgress.done()
})
export default router